package com.craftsman.demo;


import org.keycloak.KeycloakSecurityContext;
import org.keycloak.adapters.RefreshableKeycloakSecurityContext;
import org.keycloak.representations.AccessToken;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @autor ChangSir
 * @description
 * @date 2022/6/2 18:36
 */
@RestController
public class IndexController {

    /**
     * 模拟首页
     * @param request
     * @return
     */
    @RequestMapping("/n")
    public String n(HttpServletRequest request) {
        return "无需保护";
    }

    /**
     * 模拟首页
     * @param request
     * @return
     */
    @RequestMapping("/")
    public String index(HttpServletRequest request) {

        //从session中获取到keycloak上下文对象 springboot 方式
        RefreshableKeycloakSecurityContext session = (RefreshableKeycloakSecurityContext)request.getAttribute(KeycloakSecurityContext.class.getName());

        if(null == session)
            return "未登录....";

        //从上下文对象中获取到token
        AccessToken token = session.getToken();

        //其他属性，需要在客户端的mappers中设置 user attribute的属性，并且在用户页面的属性标签添加
        Map<String, Object> other = token.getOtherClaims();


        //用户名和id
        final String result = String.format(
                "<html>" +
                        "<h2>%s</h2>" +
                        "<li>userid:%s</li>" +
                        "<li>name: %s</li>" +
                        "<li>email: %s</li>" +
                        "<li>prename: %s</li>" +
                        "<li>givename: %s</li>" +
                        "<li>familyName: %s</li>" +
                        "<li>phone: %s</li>" +
                        "<li>nickname: %s</li>" +
                        "<li>%s</li>",
                token.getIssuedFor(),
                token.getSubject(),
                token.getName(),
                token.getEmail(),
                token.getPreferredUsername(),
                token.getGivenName(),
                token.getFamilyName(),
                token.getPhoneNumber(),
                token.getNickName(),
                "<a href='/demo/logout'>退出</a>");

        //获取到真实的ID
        String externalId = getRealId(token.getSubject());

        StringBuffer sb = new StringBuffer();
        other.forEach((k,v)->{
            sb.append("<li>其他属性");
            sb.append(k);
            sb.append("  值： ");
            sb.append(v.toString());
            sb.append("</li>");
        });

        return result + sb;
    }

    /**
     * 获取真实ID
     * @param id
     * @return
     */
    private String getRealId(String id) {
        if (!id.startsWith("f:")) {
            return id;
        } else {
            int providerIndex = id.indexOf(58, 2);
            return id.substring(providerIndex + 1);
        }
    }

    /**
     * 测试接口
     * @return
     */
    @RequestMapping("/hello")
    public String hello() {
        return "测试接口";
    }

    /**
     * 退出
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @GetMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.logout();
        request.isUserInRole("base_url");
        //跳转到首页(或其他需要验证的页面),进行登录验证,单点登录会自动跳转到登录页
        response.sendRedirect("/demo");
    }
}
